from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeCheckSerializer(serializers.Serializer):

    '''图片验证码序列化器'''
    image_code_id=serializers.UUIDField()
    text=serializers.CharField(max_length=4,min_length=4)

    def validate(self, attrs):

        # print(attrs)
        image_code_id= attrs['image_code_id']
        print(image_code_id)
        text=attrs['text']

        # 从redis查询真实图片验证码
        redis_conn = get_redis_connection('verify_codes')
        real_image_code_text = redis_conn.get('img_%s' % image_code_id)
        print(real_image_code_text)

        # 取到图片验证码之后,删除验证码对象,防止第三方使用这个验证码恶意攻击
        redis_conn.delete('img_%s' % image_code_id)

        real_image_code_text=real_image_code_text.decode()
        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        # 比较图片验证码
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 判断是否在60秒内,是如何获取mobile的
        # get_serializer方法在创建序列化器对象事,会补充context属性
        # context属性中包含三个值request,format,view类视图对象
        # self.context(view)
        # django的类视图对象中,kwargs属性中保存了路径提取出来的参数

        mobile=self.context['view'].kwargs['mobile']

        send_flag=redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')

        return attrs



